package com.hmall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.client.ItemClient;
import com.hmall.common.PageDTO;
import com.hmall.item.Item;
import com.hmall.mapper.SearchMapper;
import com.hmall.search.ItemDoc;

import com.hmall.search.RequestParams;

import com.hmall.service.ISearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements ISearchService {

    public static final String INDEX_NAME = "hmall";

    //注入RestHighLevelClient对象
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //定义ObjectMapper用于json与java对象转换
    private ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 自动补全
     *
     * @param key
     * @return
     */

    @Override
    public List<String> suggestion(String key) {
        try {
            //创建搜索请求对象
            SearchRequest request = new SearchRequest(INDEX_NAME);
            //自动补齐设置
            request.source().suggest(new SuggestBuilder().addSuggestion("hmSuggestion",
                    SuggestBuilders.completionSuggestion("suggestion").prefix(key).skipDuplicates(true).size(10)));
            //执行搜索
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            ArrayList<String> resultList = new ArrayList<>();
            //结果解析
            Suggest suggest = response.getSuggest();
            //获取hmSuggestion字段对象
            CompletionSuggestion hmSuggestion = suggest.getSuggestion("hmSuggestion");
            //获取options列表对象
            List<CompletionSuggestion.Entry.Option> options = hmSuggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                resultList.add(option.getText().toString());
            }
            return resultList;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤聚合条件查询
     *
     * @param requestParams
     * @return
     */

    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            //构建条件
            SearchRequest request = new SearchRequest(INDEX_NAME);
            //bool查询构造对象
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //判断key是否为空
            if (StringUtils.isNotEmpty(requestParams.getKey())) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("all", requestParams.getKey()));
            } else {
                boolQueryBuilder.must(QueryBuilders.matchAllQuery());
            }
            //判断brand是否为空
            if (StringUtils.isNotEmpty(requestParams.getBrand())) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
            }
            //判断category是否为空
            if (StringUtils.isNotEmpty(requestParams.getCategory())) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("category", requestParams.getCategory()));
            }
            //判断查询条件参数maxPrice和minPrice是否有效
            if (requestParams.getMaxPrice() != null && requestParams.getMinPrice() != null) {
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").
                        gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));
            }
            request.source().query(boolQueryBuilder);
            request.source().size(0);

            //添加聚合条件
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(100));

            //查询
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            HashMap<String, List<String>> map = new HashMap<>();
            if (response.getAggregations() != null) {
                //品牌解析
                Terms brandAgg = response.getAggregations().get("brandAgg");
                List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
                ArrayList<String> brandList = new ArrayList<>();
                for (Terms.Bucket brandAggBucket : brandAggBuckets) {
                    brandList.add(brandAggBucket.getKeyAsString());
                }
                map.put("brand", brandList);

                //购物车解析
                Terms categoryAgg = response.getAggregations().get("categoryAgg");
                List<? extends Terms.Bucket> categoryAggBuckets = categoryAgg.getBuckets();
                ArrayList<String> categoryList = new ArrayList<>();
                for (Terms.Bucket categoryAggBucket : categoryAggBuckets) {
                    categoryList.add(categoryAggBucket.getKeyAsString());
                }
                map.put("category", categoryList);
            }
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * 基本搜索功能 分类 排序 分页 高亮 广告
     *
     * @param requestParams
     * @return
     */

    @Override
    public PageDTO<ItemDoc> list(RequestParams requestParams) {
        try {
            if (requestParams.getPage() == null) requestParams.setPage(1);
            if (requestParams.getSize() == null) requestParams.setSize(5);

            //2.创建搜索请求对象 SearchRequest
            SearchRequest request = new SearchRequest(INDEX_NAME);

            //设置不限制条数
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.trackTotalHits(true);
            request.source(searchSourceBuilder);

            //创建BoolQueryBuilder来封装多个查询条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //3.判断查询条件key是否为空, 字符串非空判断StringUtils.isNotEmpty(字符串)
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(requestParams.getKey())) {
                //3.1 不为空全文检索"all"
                boolQueryBuilder.must(QueryBuilders.matchQuery("all", requestParams.getKey()));
            } else {
                //3.2 为空全文检索所有
                boolQueryBuilder.must(QueryBuilders.matchAllQuery());
            }
            //判断brand是否为空
            if (StringUtils.isNotEmpty(requestParams.getBrand())) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
            }
            //判断category是否为空
            if (StringUtils.isNotEmpty(requestParams.getCategory())) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("category", requestParams.getCategory()));
            }
            //判断查询条件参数maxPrice和minPrice是否有效
            if (requestParams.getMaxPrice() != null && requestParams.getMinPrice() != null) {
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").
                        gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));
            }
            //排序
            if (!requestParams.getSortBy().equals("default")) {
                request.source().sort(requestParams.getSortBy(), SortOrder.DESC);
            }

            //广告
            request.source().query(QueryBuilders.functionScoreQuery(
                    boolQueryBuilder,
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{// function部分
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(//functions部分
                                    QueryBuilders.termQuery("isAD", "true"),//function的filter部分
                                    ScoreFunctionBuilders.weightFactorFunction(10)//functions的weight部分
                            )
                    }
            ).boostMode(CombineFunction.MULTIPLY));

            //计算分页起始位置，公式=（当前页-1）* 每页大小
            int from = (requestParams.getPage() - 1) * requestParams.getSize();
            //设置查询分页from和size
            request.source().from(from).size(requestParams.getSize());
            //设置高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


            //执行搜索
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            //获取总记录数
            long total = hits.getTotalHits().value;
            ArrayList<ItemDoc> itemDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = objectMapper.readValue(json, ItemDoc.class);
                HighlightField highlightField = hit.getHighlightFields().get("name");
                if (highlightField != null) {
                    itemDoc.setName(highlightField.getFragments()[0].toString());
                }
                itemDocs.add(itemDoc);
            }
            return new PageDTO<>(total, itemDocs);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Autowired
    private ItemClient itemClient;

    /**
     * 获取数据库数据更新到ES里面
     *
     * @param id
     */
    @Override
    public void findById(Long id) {
        try {
            //获取Item对象
            Item item = itemClient.findById(id);
            //封装到ItemDoc
            ItemDoc itemDoc = new ItemDoc(item);
            //判断上下架
            if (item.getStatus() == 1) {
                //判断索引库是否存在该数据
                GetRequest request = new GetRequest(INDEX_NAME).id(item.getId().toString());
                GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
                String json = response.getSourceAsString();
                //判断数据是否存在，如果存在则跳过语句
                if (json == null) {
                    //进行新增数据到索引库
                    //构建文档命令
                    IndexRequest indexRequest = new IndexRequest(INDEX_NAME).id(item.getId().toString());
                    //转换为字符串
                    String json1 = objectMapper.writeValueAsString(itemDoc);
                    //填充文档数据
                    indexRequest.source(json1, XContentType.JSON);
                    //执行
                    restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                }
            } else {
                deleteById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除ES的文档数据
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        try {
            //构建删除对象
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME).id(id.toString());
            //执行
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
